<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of News
 *
 * @author Soul_man
 */
class Menu extends X3_Module_Table {

    public $encoding = 'UTF-8';

    public $tableName = 'data_menu';

    public $_fields = array(
        'id'=>array('integer[10]','unsigned','primary','auto_increment'),
        'parent_id'=>array('integer[10]','unsigned','index','default'=>'NULL','ref'=>array('Menu','id'),'tree'=>array()),
        'page_id'=>array('integer[10]','unsigned','index','default'=>'NULL','ref'=>array('Page','id'),'tree'=>array()),
        'role'=>array('string[255]','default'=>'menu'),
        'title'=>array('string[255]','language'),
        'link'=>array('string[255]','default'=>'/'),
        'weight'=>array('integer[10]','default'=>'0'),
        'status'=>array('boolean','default'=>'1'),
    );
    public static function newInstance($class=__CLASS__) {
        return parent::newInstance($class);
    }
    public static function getInstance($class=__CLASS__) {
        return parent::getInstance($class);
    }
    public static function get($arr=array(),$single=false,$class=__CLASS__) {
        return parent::get($arr,$single,$class);
    }
    public static function getByPk($pk,$class=__CLASS__) {
        return parent::getByPk($pk,$class);
    }
    public static function update($fields, $params = array(), $class = __CLASS__) {
        return parent::update($fields, $params, $class);
    }
    public static function delete($params = array(), $class = __CLASS__) {
        return parent::delete($params, $class);
    }
    public static function deleteByPk($pk, $class = __CLASS__) {
        return parent::deleteByPk($pk, $class);
    }
    public static function num_rows($params = array(), $class = __CLASS__) {
        return parent::num_rows($params, $class);
    }
    public function fieldNames() {
        return array(
            'parent_id'=>'Родитель',
            'page_id'=>'Относящийся материал',
            'title'=>'Заголовок',
            //'type'=>'Тип меню',
            'link'=>'Ссылка',
            //'role'=>'Видят только',
            'weight'=>'Порядок',
            'status'=>'Видимость',
        );
    } 
    public function moduleTitle() {
        return 'Меню';
    }
    
    public function actionFix(){
        $q = X3::db()->query("SELECT * FROM data_menu");
        while($model = mysql_fetch_assoc($q)){
            if(preg_match("/^\/page\/(.+)\.html$/", $model['link'])>0){
                $link = str_replace("/page/", "/page:", $model['link']);
                Menu::update(array('link'=>$link),array('id'=>$model['id']));
            }
        }
        echo 'OK';
        exit;
    }
    
    public function actionWeights(){
        if(!X3::user()->isAdmin() || !isset($_POST['weights']))
            throw new X3_404();
        $weights = $_POST['weights'];
        X3::db()->startTransaction();
        foreach ($weights as $weight => $id) {
            Menu::update(array('weight'=>$weight),array('id'=>$id));
        }
        X3::db()->commit();
    } 

    public function actionDelete(){
        if(!X3::user()->isAdmin() || !isset($_GET['id']))
            throw new X3_404();
        Menu::deleteByPk((int)$_GET['id']);
        exit;
    }

    public function actionAdd(){
        if(!X3::user()->isAdmin())
            throw new X3_404();
        if(IS_AJAX) $this->template->layout = NULL;
        $model = null;
        if((isset($_POST['Menu']) && isset($_POST['Menu']['id']) && ($id = $_POST['Menu']['id'])>0) || (isset($_GET['id']) && ($id = (int)$_GET['id'])>0))
            $model = Menu::getByPk($id);
        if($model == null)
            $model = new Menu;
        if(isset($_POST['Menu'])){
            $model->getTable()->acquire($_POST['Menu']);
            if($model->save())
                if(IS_AJAX)
                    die(json_encode(array('status'=>'OK','message'=>'')));
                else
                    $this->redirect('/menu/add/id/'.$model->id);
            elseif(IS_AJAX)
                die(json_encode(array('status'=>'ERROR','message'=>X3_Html::errorSummary($model).X3::db()->getErrors())));
        }
        $this->template->render('form',array('model'=>$model));
        if(IS_AJAX) exit;
    }

    public function getDefaultScope() {
        return array(
            '@order'=>array('weight')
        );
    }
    
    public function beforeValidate() {
//        if($this->parent_id == 0)
//            $this->parent_id = null;
        return true;
    }
    
    public function afterSave() {
        if(is_file('sitemap.xml'))
            @unlink('sitemap.xml');
    }
}
?>
